<template>
  <div class="new-products-section">
    <div class="section-header">
      <h2 class="title">
        <span class="title-text">新品推荐</span>
        <span class="subtitle">新潮好货 抢先拥有</span>
      </h2>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <div class="loading-spinner"></div>
      <p>正在加载新品...</p>
    </div>

    <!-- 错误状态 -->
    <div v-else-if="error" class="error-container">
      <p>加载失败: {{ error }}</p>
      <button @click="fetchNewProducts" class="retry-button">重试</button>
    </div>

    <!-- 空状态 -->
    <div v-else-if="!products || products.length === 0" class="empty-container">
      <p>暂无新品</p>
    </div>

    <!-- 滚动加载状态 -->
    <div v-if="scrollLoading" class="scroll-loading">
      <div class="loading-spinner small"></div>
      <p>正在加载更多...</p>
    </div>

    <!-- 没有更多数据 -->
    <div v-if="!hasMore && products.length > 0" class="no-more-data">
      <p>没有更多新品了</p>
    </div>

    <!-- 正常状态 -->
    <div v-else class="products-container">
      <div
        v-for="(product, index) in products"
        :key="product.goods_id || index"
        :class="['product-card', { 'last-item': index === products.length - 1 }]"
        @click="goToProductDetail(product.goods_id)"
      >
        <!-- 秒杀标签 - 优先显示 -->
        <div v-if="product.is_flash_sale" class="flash-sale-tag">
          <span class="badge-text">秒杀</span>
        </div>

        <!-- 其他标签 -->
        <div v-else-if="getProductBadge(product)" class="product-badge">
          <span class="badge-text">{{ getProductBadge(product) }}</span>
        </div>

        <div class="product-image">
          <div class="image-container">
            <img
              v-if="product.goods_cover_img"
              v-lazy="product.goods_cover_img"
              :alt="product.goods_name"
              @error="handleImageError"
            />
            <div v-else class="image-placeholder" :style="{ backgroundColor: getRandomColor() }">
              <span class="placeholder-text">商品图片</span>
            </div>
          </div>
        </div>

        <div class="product-info">
          <h3 class="product-name">{{ product.goods_name }}</h3>
          <p class="product-desc">{{ product.goods_intro || '暂无描述' }}</p>
          <div class="price-section">
            <span class="current-price">¥{{ formatPrice(product.goods_price) }}</span>
            <span
              class="original-price"
              v-if="
                product.market_price &&
                parseFloat(product.market_price) > parseFloat(product.goods_price)
              "
            >
              ¥{{ formatPrice(product.market_price) }}
            </span>
            <span class="sales-count" v-if="product.goods_sales > 0"
              >已售{{ product.goods_sales }}件</span
            >
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, nextTick, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { goodsApi, type GoodsBase, formatPrice, isNewProduct, isHotProduct } from '@/api/goods'
const router = useRouter()

// 滚动加载状态
const scrollLoading = ref(false)
const hasMore = ref(true)
const currentPage = ref(1)
const pageSize = 10

// Intersection Observer 用于懒加载
let observer: IntersectionObserver | null = null
const observeLastItem = () => {
  if (observer) {
    observer.disconnect()
  }

  const items = document.querySelectorAll('.product-card')
  if (items.length === 0) return

  const lastItem = items[items.length - 1]
  observer = new IntersectionObserver(
    async ([entry]) => {
      if (entry.isIntersecting && hasMore.value && !scrollLoading.value) {
        console.log('检测到滚动到底部，开始加载更多新品...')
        await loadMoreProducts()
      }
    },
    {
      rootMargin: '200px',
      threshold: 0.1,
    },
  )

  observer.observe(lastItem)
  console.log('已设置观察器监控最后一个新品元素')
}

// 加载更多商品
const loadMoreProducts = async () => {
  if (scrollLoading.value || !hasMore.value) return

  scrollLoading.value = true
  currentPage.value++

  try {
    const response = await goodsApi.getNewGoods({
      limit: pageSize,
      offset: (currentPage.value - 1) * pageSize,
    })

    console.log('加载更多新品API响应:', response)
    // 打印新加载的数据
    console.group('新加载的新品数据')
    console.table(
      response.results.map((p) => ({
        id: p.goods_id,
        name: p.goods_name,
        price: p.goods_price,
      })),
    )
    console.groupEnd()

    if (response && Array.isArray(response.results)) {
      const newProducts = response.results
      products.value = [...products.value, ...newProducts]
      hasMore.value = newProducts.length === pageSize

      // 延迟观察新项目，确保DOM已更新
      setTimeout(observeLastItem, 100)
    } else {
      hasMore.value = false
    }
  } catch (err) {
    console.error('加载更多新品失败:', err)
    hasMore.value = false
  } finally {
    scrollLoading.value = false
  }
}
// 商品数据
const products = ref<GoodsBase[]>([])
const loading = ref(true)
const error = ref<string | null>(null)

// 随机颜色生成（用于占位图）
const colors = [
  '#FFECB3',
  '#FFCCBC',
  '#FFF9C4',
  '#C8E6C9',
  '#B3E5FC',
  '#E1BEE7',
  '#F8BBD0',
  '#DCEDC8',
  '#FFE0B2',
  '#E0F7FA',
]

const getRandomColor = () => {
  return colors[Math.floor(Math.random() * colors.length)]
}

// 获取商品徽章
const getProductBadge = (product: GoodsBase): string | undefined => {
  // 秒杀标签优先显示，已经在模板中单独处理
  if (isNewProduct(product)) return '新品'
  if (isHotProduct(product)) return '热卖'
  if (product.is_recommend) return '推荐'
  if (parseFloat(product.market_price) > parseFloat(product.goods_price)) return '特惠'
  return undefined
}

// 图片加载失败处理
const handleImageError = (event: Event) => {
  const imgElement = event.target as HTMLImageElement
  imgElement.style.display = 'none'
  const parent = imgElement.parentElement
  if (parent) {
    const placeholder = document.createElement('div')
    placeholder.className = 'image-placeholder'
    placeholder.style.backgroundColor = getRandomColor()
    const text = document.createElement('span')
    text.className = 'placeholder-text'
    text.textContent = '图片加载失败'
    placeholder.appendChild(text)
    parent.appendChild(placeholder)
  }
}

// 获取新品数据
const fetchNewProducts = async () => {
  try {
    loading.value = true
    error.value = null
    // 调用API获取新品
    const response = await goodsApi.getNewGoods({ limit: 10 })
    products.value = response.results || []
  } catch (err) {
    console.error('获取新品数据失败:', err)
    error.value = err instanceof Error ? err.message : '未知错误'
  } finally {
    loading.value = false
  }
}
const goToProductDetail = (productId: number) => {
  console.log('跳转传递的productId:', productId, '类型:', typeof productId)
  if (isNaN(productId) || productId <= 0) {
    console.error('无效的productId，不跳转:', productId)
    return // 终止跳转，避免传递无效参数
  }
  router.push(`/product/${productId}`)
  console.log(productId)
}

// 监听products变化重新设置观察器
watch(products, () => {
  nextTick(() => {
    observeLastItem()
  })
})

// 组件挂载时获取数据
onMounted(() => {
  fetchNewProducts().then(() => {
    // 初始加载完成后设置观察器
    observeLastItem()
  })
})

// 组件卸载时清理观察器
onUnmounted(() => {
  if (observer) {
    observer.disconnect()
  }
})
</script>

<style scoped lang="scss">
.new-products-section {
  background: white;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  padding: 20px;
  margin-bottom: 30px;

  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 15px;
    border-bottom: 1px solid #f0f0f0;

    .title {
      display: flex;
      align-items: baseline;
      gap: 15px;

      .title-text {
        font-size: 22px;
        font-weight: 700;
        color: #333;
        position: relative;

        &::after {
          content: '';
          position: absolute;
          bottom: -5px;
          left: 0;
          width: 100%;
          height: 3px;
          background: linear-gradient(to right, #4db6ac, #81c784);
        }
      }

      .subtitle {
        font-size: 16px;
        color: #666;
      }
    }

    .view-more {
      color: #666;
      font-size: 14px;
      text-decoration: none;
      display: flex;
      align-items: center;

      &::after {
        content: '→';
        margin-left: 5px;
        transition: transform 0.2s;
      }

      &:hover {
        color: #4db6ac;

        &::after {
          transform: translateX(3px);
        }
      }
    }
  }

  .loading-container,
  .error-container,
  .empty-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 40px 0;
    color: #666;

    .loading-spinner {
      width: 40px;
      height: 40px;
      border: 3px solid #f0f0f0;
      border-top: 3px solid #4db6ac;
      border-radius: 50%;
      animation: spin 1s linear infinite;
      margin-bottom: 16px;
    }

    .retry-button {
      margin-top: 16px;
      padding: 8px 16px;
      background: #4db6ac;
      color: white;
      border: none;
      border-radius: 4px;
      cursor: pointer;
      transition: background 0.2s;

      &:hover {
        background: #26a69a;
      }
    }
  }

  // 滚动加载状态
  .scroll-loading {
    grid-column: 1 / -1;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 30px 0;

    .loading-spinner.small {
      width: 24px;
      height: 24px;
      border-width: 2px;
      margin-bottom: 12px;
    }

    p {
      color: #666;
      font-size: 14px;
    }
  }

  // 没有更多数据
  .no-more-data {
    grid-column: 1 / -1;
    text-align: center;
    padding: 30px 0;
    color: #999;
    font-size: 14px;
  }

  .products-container {
    display: grid;
    grid-template-columns: repeat(5, minmax(0, 1fr));
    gap: 16px;
    padding: 0 20px;

    .product-card {
      position: relative;
      background: #ffffff;
      border: 1px solid #f0f0f0;
      border-radius: 12px;
      transition: all 0.3s ease;
      overflow: hidden;
      padding: 16px;
      display: flex;
      flex-direction: column;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);

      &:hover {
        transform: translateY(-5px);
        box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
      }
    }

    .product-badge {
      position: absolute;
      top: 10px;
      right: 10px;
      padding: 3px 8px;
      background: #ff4e50;
      color: white;
      font-size: 12px;
      border-radius: 3px;
      z-index: 5;
    }

    .flash-sale-tag {
      position: absolute;
      top: 10px;
      left: 10px;
      background: linear-gradient(135deg, #ff4e50, #f9002f);
      color: white;
      padding: 4px 8px;
      border-radius: 4px;
      font-size: 12px;
      font-weight: bold;
      z-index: 10; /* 确保秒杀标签在最上层 */
      box-shadow: 0 2px 8px rgba(255, 0, 0, 0.3);
    }

    .product-image {
      border-radius: 6px;
      overflow: hidden;
      margin-bottom: 8px;

      .image-container {
        width: 100%;
        aspect-ratio: 1/1;
        position: relative;

        img {
          width: 100%;
          height: 100%;
          object-fit: cover;
          transition: transform 0.3s ease;
        }

        .image-placeholder {
          width: 100%;
          height: 100%;
          display: flex;
          align-items: center;
          justify-content: center;

          .placeholder-text {
            color: #999;
            font-size: 14px;
          }
        }
      }
    }

    .product-info {
      flex: 1;
      display: flex;
      flex-direction: column;

      .product-name {
        font-size: 16px;
        font-weight: 600;
        margin-bottom: 8px;
        color: #333;
        overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        min-height: 46px;
      }

      .product-desc {
        font-size: 13px;
        color: #888;
        margin-bottom: 15px;
        flex: 1;
        overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
      }

      .price-section {
        display: flex;
        align-items: center;
        flex-wrap: wrap;

        .current-price {
          font-size: 18px;
          font-weight: 700;
          color: #ff4e50;
          margin-right: 8px;
        }

        .original-price {
          font-size: 13px;
          color: #999;
          text-decoration: line-through;
          margin-right: 8px;
        }

        .sales-count {
          font-size: 13px;
          color: #666;
          margin-left: auto;
        }
      }
    }
  }

  @media (max-width: 1200px) {
    .products-container {
      grid-template-columns: repeat(4, minmax(0, 1fr));
    }
  }

  @media (max-width: 768px) {
    .products-container {
      grid-template-columns: repeat(3, minmax(0, 1fr));
      gap: 12px;
      padding: 0 15px;
    }
  }

  @media (max-width: 480px) {
    .products-container {
      grid-template-columns: repeat(2, minmax(0, 1fr));
      gap: 10px;
      padding: 0 10px;
    }
  }
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}
</style>
